package com.dd.shop4j.common.utils.interceptor.form;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 表单令牌管理实现类
 * @author tangshu
 *
 */
public class FormTokenManagerImpl implements IFormTokenManager {

	//保存到session中的tonken名称
	public static final String formTokenSessionName = "SESSION_FORM_TOKEN";

	private HttpSession getSession(HttpServletRequest request) {
		return request.getSession();
	}
	
	@Override
	public void initFormToken(HttpServletRequest request) {
		HttpSession session = getSession(request);
		session.setAttribute(formTokenSessionName, new FormToken());
	}

	@Override
	public void destoryFormToken(HttpServletRequest request) {
		HttpSession session = getSession(request);
		session.removeAttribute(formTokenSessionName);
	}
	
	@Override
	public boolean validateFormToken(HttpServletRequest request, String token) {
		FormToken formToken = getFormToken(request);
		return formToken == null || formToken.getToken().equals(token);
	}
	
	@Override
	public FormToken getFormToken(HttpServletRequest request) {
		HttpSession session = getSession(request);
		return (FormToken) session.getAttribute(formTokenSessionName);
	}

}
